<!--登录页面-->
<template>
  <h1>登录页面</h1>
  <el-card style="width: 450px;margin: 0 auto;padding:20px 10px 0 0;">
    <el-form label-width="60px">
      <el-form-item label="用户名">
        <el-input placeholder="请输入用户名" v-model="user.username"></el-input>
      </el-form-item>
      <el-form-item label="密码">
        <el-input placeholder="请输入密码" type="password" v-model="user.password" @keydown.enter="login()"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" style="width:100%;" @click="login()">登录</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script setup>
  import {ref} from "vue";
  import qs from "qs";
  import {ElMessage} from "element-plus";
  import axios from "axios";
  import router from "@/router";

  const user = ref({username:'',password:''});
  const login = ()=>{
    //将JS对象转为查询字符串格式
    let data = qs.stringify(user.value);
    //console.log(data);//username=tom&password=666
    axios.post('http://localhost:8080/v1/users/login',data)
    .then((response)=>{
      if(response.data.code==2001){
        let user = response.data.data;
        ElMessage.success('登录成功!欢迎'+user.nickname+'回来!');
        //localStorage以字符串键值对的方式存储数据,关闭浏览器或PC都不会清除数据
        //JSON.stringify(user)将JS对象user转为JSON格式的字符串
        localStorage.setItem('user',JSON.stringify(user));
        router.push('/');
      }else{
        ElMessage.error(response.data.msg);
      }
    })
  }
</script>

<style scoped>

</style>